<template>
  <div class="output-files-container">
    <el-card class="files-card">
      <template #header>
        <div class="card-header">
          <h3>
            <span
              v-if="currentTab === 'current'"
              style="cursor: pointer; user-select: all;"
              @click="copyOutputPath"
              title="点击复制输出路径"
            >
              输出文件 ({{ files[0]?.output_path.replace(files[0]?.name, '') || '' }})[总数：{{ files.length }}]
            </span>
            <span v-else>
              历史视频
            </span>
          </h3>
          <div class="header-actions">
            <div v-if="loading || historyLoading" class="loading-indicator">
              <el-icon class="is-loading"><i class="el-icon-loading"></i></el-icon>
              <span>加载中...</span>
            </div>
            <el-button size="small" @click="refreshFiles" :disabled="loading || historyLoading">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 标签页切换 -->
      <div class="custom-tabs">
        <div class="tab-headers">
          <div class="tab-header" :class="{ 'active': currentTab === 'current' }" @click="switchTab('current')">
            当前输出
          </div>
          <div class="tab-header" :class="{ 'active': currentTab === 'history' }" @click="switchTab('history')"
            id="id_1">
            历史视频
          </div>
        </div>

        <!-- 当前输出标签内容 -->
        <div v-show="currentTab === 'current'" class="tab-content">
          <!-- 批量下载按钮 -->
          <div class="batch-actions" v-if="files.length > 0">
            <el-button type="primary" size="small" @click="batchDownload" :disabled="!selectedCurrentFiles.length">
              批量下载 ({{ selectedCurrentFiles.length }})
            </el-button>
            <el-button size="small" @click="toggleSelectAll('current')">
              {{ isAllCurrentSelected ? '取消全选' : '全选' }}
            </el-button>
          </div>

          <!-- 表格 -->
          <el-table :data="files" style="width: 100%" @selection-change="handleCurrentSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="文件名" min-width="200" show-overflow-tooltip />
            <el-table-column prop="audio_name" label="音频文件名称" width="180" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" @click="previewFile(scope.row)">
                  预览
                </el-button>
                <el-button size="small" type="success" @click="downloadFile(scope.row)">
                  下载
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 显示空状态 -->
          <div v-if="files.length === 0 && !loading" class="empty-state">
            <el-empty description="暂无输出文件" />
          </div>
        </div>

        <!-- 历史视频标签内容 -->
        <div v-show="currentTab === 'history'" class="tab-content">
          <div class="history-header">
            <div class="history-search">
              <el-input v-model="historySearchQuery" placeholder="搜索历史视频" clearable prefix-icon="el-icon-search"
                style="margin-bottom: 15px;" />
            </div>

            <!-- 历史视频批量下载按钮 -->
            <div class="batch-actions" v-if="filteredHistoryVideos.length > 0">
              <el-button type="primary" size="small" @click="batchDownloadHistory"
                :disabled="!selectedHistoryFiles.length">
                批量下载 ({{ selectedHistoryFiles.length }})
              </el-button>
              <el-button size="small" @click="toggleSelectAll('history')">
                {{ isAllHistorySelected ? '取消全选' : '全选' }}
              </el-button>
            </div>
          </div>

          <!-- 表格 -->
          <el-table :data="filteredHistoryVideos" style="width: 100%" @selection-change="handleHistorySelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="filename" label="文件名" min-width="200" show-overflow-tooltip />
            <el-table-column prop="created_at" label="创建时间" width="180" />
            <el-table-column prop="category" label="分类" width="120" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" @click="previewHistoryFile(scope.row)">
                  预览
                </el-button>
                <el-button size="small" type="success" @click="downloadHistoryFile(scope.row)">
                  下载
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="historyVideos.length === 0 && !historyLoading" class="empty-state">
            <el-empty description="暂无历史视频" />
          </div>

          <!-- 分页 -->
          <div class="pagination-container" v-if="historyVideos.length > 0">
            <a href="#id_1"
              style="background-color: #409eff;
              margin-right: 20px;;
              text-decoration: none; color: #fff; border-radius: 4px; font-size: 12px; padding: .5em;">回到全选</a>

            <el-pagination background layout="sizes, prev, pager, next, jumper" :total="paginationInfo.totalCount"
              :page-size="paginationInfo.pageSize" :page-sizes="[10, 20, 50, 100]"
              :current-page="paginationInfo.currentPage" @current-change="handleHistoryPageChange"
              @size-change="handleHistorySizeChange" />
          </div>

        </div>
      </div>
    </el-card>

    <!-- 批量下载进度弹窗 -->
    <el-dialog v-model="batchDownloadVisible" title="批量下载进度" width="500px" :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="downloadCount === totalDownloads">
      <div class="download-progress">
        <el-progress :percentage="Math.round((downloadCount / totalDownloads) * 100)"
          :status="downloadCount === totalDownloads ? 'success' : ''"></el-progress>
        <div class="download-status">
          正在下载 {{ downloadCount }}/{{ totalDownloads }} 个文件
        </div>
        <div class="download-tip" v-if="downloadCount > 0">
          <i class="el-icon-info"></i>
          部分浏览器可能会阻止多个文件下载，请留意浏览器提示
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchDownloadVisible = false" :disabled="downloadCount !== totalDownloads">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, ref, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import mergeService from '@/views/Mergeview/services/mergeService';
import {copyToClipboard} from '@/utils/common'

export default defineComponent({
  name: 'OutputFilesTable',
  props: {
    files: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['refresh'],
  setup(props, { emit }) {
    // 标签页状态
    const currentTab = ref('current');
    // 历史视频数据
    const historyVideos = ref([]);
    const historyLoading = ref(false);
    const historySearchQuery = ref('');

    // 选中的文件
    const selectedCurrentFiles = ref([]);
    const selectedHistoryFiles = ref([]);

    // 批量下载状态
    const batchDownloadVisible = ref(false);
    const downloadCount = ref(0);
    const totalDownloads = ref(0);

    const copyOutputPath = () => {
      const outputPath = props.files[0].output_path.replace(props.files[0].name, '');
      if (outputPath) {
        copyToClipboard(outputPath)
      }
    };
    // 计算是否全选
    const isAllCurrentSelected = computed(() => {
      return props.files.length > 0 && selectedCurrentFiles.value.length === props.files.length;
    });

    const isAllHistorySelected = computed(() => {
      return filteredHistoryVideos.value.length > 0 &&
        selectedHistoryFiles.value.length === filteredHistoryVideos.value.length;
    });

    const handleHistorySizeChange = (size) => {
      paginationInfo.value.pageSize = size;
      paginationInfo.value.currentPage = 1; // Reset to first page when changing page size
      loadHistoryVideos(1); // Reload with new page size
    };

    // 分页信息
    const paginationInfo = ref({
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      totalPages: 0
    });

    // 处理标签切换
    const switchTab = (tab) => {
      currentTab.value = tab;
      if (tab === 'history' && historyVideos.value.length === 0) {
        loadHistoryVideos();
      }
    };

    // 过滤历史视频
    const filteredHistoryVideos = computed(() => {
      if (!historySearchQuery.value) {
        return historyVideos.value;
      }

      const query = historySearchQuery.value.toLowerCase();
      return historyVideos.value.filter(video =>
        (video.filename && video.filename.toLowerCase().includes(query)) ||
        (video.category && video.category.toLowerCase().includes(query))
      );
    });

    // 处理当前文件选择变化
    const handleCurrentSelectionChange = (selection) => {
      selectedCurrentFiles.value = selection;
    };

    // 处理历史文件选择变化
    const handleHistorySelectionChange = (selection) => {
      selectedHistoryFiles.value = selection;
    };

    // 切换全选/取消全选
    const toggleSelectAll = (tabType) => {
      // 使用表格的方法来切换选择状态
      const table = document.querySelector('.el-table');
      if (!table) return;

      if (tabType === 'current') {
        if (isAllCurrentSelected.value) {
          // 取消全选
          table.__vue__.clearSelection();
        } else {
          // 全选
          props.files.forEach(row => {
            table.__vue__.toggleRowSelection(row, true);
          });
        }
      } else {
        if (isAllHistorySelected.value) {
          // 取消全选
          table.__vue__.clearSelection();
        } else {
          // 全选
          filteredHistoryVideos.value.forEach(row => {
            table.__vue__.toggleRowSelection(row, true);
          });
        }
      }
    };

    // 加载历史视频
    const loadHistoryVideos = async (page = 1) => {
      try {
        historyLoading.value = true;
        const response = await mergeService.getVideoHistory(page, paginationInfo.value.pageSize);

        if (response && response.success && response.data) {
          historyVideos.value = response.data.records || [];

          // 更新分页信息
          if (response.data.pagination) {
            paginationInfo.value = {
              currentPage: response.data.pagination.page || 1,
              pageSize: response.data.pagination.page_size || 10,
              totalCount: response.data.pagination.total_count || 0,
              totalPages: response.data.pagination.total_pages || 1
            };
          }
        } else {
          ElMessage.error('获取历史视频失败');
        }
      } catch (error) {
        console.error('获取历史视频失败:', error);
        ElMessage.error('获取历史视频失败: ' + (error.message || '未知错误'));
      } finally {
        historyLoading.value = false;
      }
    };

    // 处理历史视频分页变化
    const handleHistoryPageChange = (page) => {
      paginationInfo.value.currentPage = page;
      loadHistoryVideos(page);
    };

    // 刷新当前文件列表
    const refreshFiles = () => {
      if (currentTab.value === 'current') {
        emit('refresh');
      } else {
        loadHistoryVideos(paginationInfo.value.currentPage);
      }
    };

    // 预览文件
    const previewFile = (file) => {
      if (!file || !file.output_path) {
        ElMessage.warning('无法预览文件，路径不存在');
        return;
      }

      const fileUrl = getFileUrl(file);
      window.open(fileUrl, '_blank');
    };

    // 预览历史文件
    const previewHistoryFile = (file) => {
      if (!file || !file.file_path) {
        ElMessage.warning('无法预览文件，路径不存在');
        return;
      }

      const fileUrl = getHistoryFileUrl(file);
      window.open(fileUrl, '_blank');
    };

    // 下载文件
    const downloadFile = (file) => {
      if (!file || !file.output_path) {
        ElMessage.warning('无法下载文件，路径不存在');
        return;
      }

      const fileUrl = getFileUrl(file);
      const a = document.createElement('a');
      a.href = fileUrl;
      a.download = file.name || 'download';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      ElMessage.success('开始下载文件');
    };

    // 下载历史文件
    const downloadHistoryFile = (file) => {
      if (!file || !file.file_path) {
        ElMessage.warning('无法下载文件，路径不存在');
        return;
      }

      const fileUrl = getHistoryFileUrl(file);
      const a = document.createElement('a');
      a.href = fileUrl;
      a.download = file.filename || file.name || 'download';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      ElMessage.success('开始下载文件');
    };

    // 批量下载当前文件
    const batchDownload = async () => {
      if (selectedCurrentFiles.value.length === 0) {
        ElMessage.warning('请选择要下载的文件');
        return;
      }

      // 显示下载进度对话框
      batchDownloadVisible.value = true;
      downloadCount.value = 0;
      totalDownloads.value = selectedCurrentFiles.value.length;

      // 使用延迟来防止浏览器阻止多个下载
      for (let i = 0; i < selectedCurrentFiles.value.length; i++) {
        const file = selectedCurrentFiles.value[i];
        if (!file || !file.output_path) continue;

        await new Promise(resolve => setTimeout(resolve, 1000)); // 延迟1秒

        try {
          const fileUrl = getFileUrl(file);
          const a = document.createElement('a');
          a.href = fileUrl;
          a.download = file.name || `download_${i}`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          downloadCount.value++;
        } catch (error) {
          console.error('下载文件失败:', error);
        }
      }

      ElMessage.success(`已开始下载 ${downloadCount.value} 个文件`);
    };

    // 批量下载历史文件
    const batchDownloadHistory = async () => {
      if (selectedHistoryFiles.value.length === 0) {
        ElMessage.warning('请选择要下载的文件');
        return;
      }

      // 显示下载进度对话框
      batchDownloadVisible.value = true;
      downloadCount.value = 0;
      totalDownloads.value = selectedHistoryFiles.value.length;

      // 使用延迟来防止浏览器阻止多个下载
      for (let i = 0; i < selectedHistoryFiles.value.length; i++) {
        const file = selectedHistoryFiles.value[i];
        if (!file || !file.file_path) continue;

        await new Promise(resolve => setTimeout(resolve, 1000)); // 延迟1秒

        try {
          const fileUrl = getHistoryFileUrl(file);
          const a = document.createElement('a');
          a.href = fileUrl;
          a.download = file.filename || `download_${i}`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          downloadCount.value++;
        } catch (error) {
          console.error('下载文件失败:', error);
        }
      }

      ElMessage.success(`已开始下载 ${downloadCount.value} 个文件`);
    };

    // 获取当前文件URL
    const getFileUrl = (file) => {
      if (!file || !file.output_path) return '';

      // 提取public之后的路径
      const pathParts = file.output_path.split('\\');
      const publicIndex = pathParts.findIndex(part => part === 'public');

      if (publicIndex !== -1) {
        // 构建URL路径
        const relativePath = pathParts.slice(publicIndex).join('/');
        return `${window.location.origin}/${relativePath}`;
      }

      // 如果没有找到public路径，使用原始路径但替换反斜杠
      return `${window.location.origin}/public/videos/${file.name}`;
    };

    // 获取历史文件URL
    const getHistoryFileUrl = (file) => {
      if (!file || !file.file_path) return '';

      // 提取public之后的路径
      const pathParts = file.file_path.split('\\');
      const publicIndex = pathParts.findIndex(part => part === 'public');

      if (publicIndex !== -1) {
        // 构建URL路径
        const relativePath = pathParts.slice(publicIndex).join('/');
        return `${window.location.origin}/${relativePath}`;
      }

      // 如果没有找到public路径，使用原始路径但替换反斜杠
      return `${window.location.origin}/public/videos/${file.filename || file.name || file.id}`;
    };

    onMounted(() => {
      // 如果默认是历史标签，则加载历史数据
      if (currentTab.value === 'history') {
        loadHistoryVideos();
      }
    });

    return {
      currentTab,
      switchTab,
      historyVideos,
      historyLoading,
      historySearchQuery,
      filteredHistoryVideos,
      paginationInfo,
      selectedCurrentFiles,
      selectedHistoryFiles,
      isAllCurrentSelected,
      isAllHistorySelected,
      batchDownloadVisible,
      downloadCount,
      totalDownloads,
      refreshFiles,
      previewFile,
      previewHistoryFile,
      downloadFile,
      downloadHistoryFile,
      handleHistoryPageChange,
      handleCurrentSelectionChange,
      handleHistorySelectionChange,
      toggleSelectAll,
      batchDownload,
      batchDownloadHistory,
      handleHistorySizeChange,
      copyOutputPath,
    };
  }
});
</script>

<style scoped>
.output-files-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 自定义标签样式 */
.custom-tabs {
  display: flex;
  flex-direction: column;
}

.tab-headers {
  display: flex;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.tab-header {
  padding: 10px 20px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  margin-right: 10px;
  font-weight: 500;
  color: #606266;
  transition: all 0.3s;
}

.tab-header.active {
  border-bottom: 2px solid #409EFF;
  color: #409EFF;
}

.tab-content {
  min-height: 350px;
}

/* 批量下载按钮区域 */
.batch-actions {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

/* 历史页面头部区域 */
.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.history-search {
  flex: 1;
  margin-right: 15px;
}

.empty-state {
  padding: 50px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 添加加载指示器样式 */
.loading-indicator {
  display: flex;
  align-items: center;
  margin-right: 10px;
  color: #909399;
  font-size: 14px;
}

.loading-indicator .el-icon-loading {
  margin-right: 5px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 下载进度样式 */
.download-progress {
  padding: 20px 10px;
}

.download-status {
  margin-top: 15px;
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.download-tip {
  margin-top: 20px;
  background-color: #ecf8ff;
  padding: 10px;
  border-radius: 4px;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
  display: flex;
  align-items: center;
}

.download-tip i {
  color: #409EFF;
  margin-right: 5px;
  font-size: 16px;
}

.dialog-footer {
  text-align: center;
}
</style>